<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>日期格式转换</title>
    <script>
        window.onload = function () {
            // 获取DOM元素
            let inputDate = document.getElementById('inputDate');
            let outputDate = document.getElementById('outputDate');
            let currentDateButton = document.getElementById('currentDateButton');

            // 定义格式化日期的函数
            function formatDateString(dateStr) {
                let dateParts = dateStr.match(
                    /(\d{4})年(\d{1,2})月(\d{1,2})日(\d{1,2}):(\d{1,2}):(\d{1,2})/
                );
                if (dateParts) {
                    let formattedDate =
                        dateParts[1].slice(-2) +
                        dateParts[2].padStart(2, '0') +
                        dateParts[3].padStart(2, '0') +
                        dateParts[4].padStart(2, '0') +
                        dateParts[5].padStart(2, '0') +
                        dateParts[6].padStart(2, '0');
                    return formattedDate;
                } else {
                    return 'Invalid date format';
                }
            }

            // 时间转为年月日形势
            function formatDateYearMon(date) {
                var year = date.getFullYear();
                var month = (date.getMonth() + 1).toString().padStart(2, '0');
                var day = date.getDate().toString().padStart(2, '0');
                var hours = date.getHours().toString().padStart(2, '0');
                var minutes = date.getMinutes().toString().padStart(2, '0');
                var seconds = date.getSeconds().toString().padStart(2, '0');

                return year + '年' + month + '月' + day + '日' + hours + ':' + minutes + ':' + seconds;
            }

            // 添加事件监听器，当输入框内容改变时调用formatDateString并更新输出
            inputDate.addEventListener('input', function () {
                let formatted = formatDateString(this.value);
                outputDate.textContent = formatted;
            });

            // 写入最新时间，并更新输出
            function setNewTime() {
                let now = new Date();
                let formattedNow = formatDateYearMon(now);
                inputDate.value = formattedNow;
                // 自动触发input的change事件来更新输出
                let event = new Event('input', { bubbles: true });
                inputDate.dispatchEvent(event);
            }

            // 新增按钮点击事件处理函数
            currentDateButton.addEventListener('click', setNewTime);
            setNewTime();
        };
    </script>
</head>

<body>
    <h2>日期格式转换工具</h2>
    <p>请输入日期（如：2024年6月21日17:04:18）：</p>
    <input type="text" id="inputDate" placeholder="在此输入日期" />

    <button id="currentDateButton">添加当前时间</button>

    <p>转换后的日期：</p>
    <span id="outputDate"></span>
</body>

</html>